package com.apiauto.http_util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import com.apiauto.log.Log;

/**
 * PS:响应工具类
 * @author lkk
 *
 */
public class Response{
	/**
	 * PS:获取响应头部信息
	 * @param httpResponse 响应对象
	 * @return 响应头字典
	 */
	public static Map<String,String> getResponseHeaders(CloseableHttpResponse httpResponse) {
		//存储响应头信息的Map
		Map<String,String> responseHeaders = new HashMap();
		//获取响应头对象数组
		Header[] headers = httpResponse.getAllHeaders();
		//遍历响应头数组将key,value塞入map
		for(Header header:headers) {
			responseHeaders.put(header.getName(), header.getValue());
		}
		return responseHeaders;
	}
	
	/**
	 * PS:获取响应主体信息
	 * @param httpResponse 响应对象
	 * @return 响应主体信息
	 */
	public static String getResponseEntity(CloseableHttpResponse httpResponse) {
		//最终返回的字符串信息
		String responseEntity = null;
		//获取主体信息对象
		HttpEntity entity = httpResponse.getEntity();
		try {
			//将主体信息对象转为字符串
			responseEntity = EntityUtils.toString(entity, "UTF-8");
		} catch (ParseException e) {
			Log.error("+++++响应主体信息转换异常+++++");
		} catch (IOException e) {
			Log.error("+++++响应主体信息IO异常+++++");
		}
		return responseEntity;
	}
	
	/**
	 * PS:获取响应码
	 * @param httpResponse 响应对象
	 * @return 状态码
	 */
	public static int getResponseCode(CloseableHttpResponse httpResponse) {
		//获取响应头对象
		StatusLine statusLine = httpResponse.getStatusLine();
		//获取响应码
		int responseCode = statusLine.getStatusCode();
		return responseCode;
	}
}
